#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/10 11:58
    Desc  :
--------------------------------------
"""
import json

from flask import Blueprint, render_template, request
from application import app
from common.libs.JsonResponseUtils import JsonResponse
from common.libs.JwtUtils import verify_jwt
from common.libs.PhoneCheckUtils import PhoneCheckUtils
from common.libs.QuerySetUtils import QuerySetUtils
from common.libs.paginationUtils import PaginationUtils, ListPaginationUtils
from common.libs.queryListUtils import QueryListUtils
from servers.decorator.UserDecorator import check_param
from servers.models.userModel import User
from servers.servers.UserServices import UserServices

user_route = Blueprint('organizeuser', __name__)
ADMIN = 101


# 用户列表
@user_route.route('/list', methods = ["POST"])
@check_param(paramList = ['page', 'size'])
def userList():
    try:
        form = {} if not request.json else dict(request.json)
        form['admin'] = ADMIN
        data = UserServices().pagination(**form)
        return JsonResponse(code = 20000, data = data, message = '请求成功').jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 新增用户
@user_route.route('/add', methods = ["POST"])
@check_param(paramList = ['username', 'password'])
def userAdd():
    try:
        form = {} if not request.json else dict(request.json)
        username, phone = form.get('username'), form.get('phone')
        form = QuerySetUtils(User).filterField(form)
        form['admin'] = ADMIN
        if not PhoneCheckUtils(phone).phone_check():
            return JsonResponse(code = 40006, data = None, message = "phone格式错误").jsonExit()
        if User.objects(username = username, admin = ADMIN).count() != 0:
            return JsonResponse(code = 40003, data = None, message = "username已存在").jsonExit()
        if User.objects(phone = phone, admin = ADMIN).count() != 0:
            return JsonResponse(code = 40003, data = None, message = "phone已被使用").jsonExit()
        user = User(**form)
        user.save()
        return JsonResponse(code = 20000, data = user.to_json(), message = "请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 用户详情
@user_route.route('/info', methods = ['POST'])
def userInfo():
    try:
        accesstoken = request.headers.get('accesstoken')
        if verify_jwt(accesstoken) is None:
            return JsonResponse(code = 40004, data = None, message = "accesstoken失效").jsonExit()
        username = verify_jwt(accesstoken).get('username')
        print(verify_jwt(accesstoken))
        user = User.objects(username = username, admin = ADMIN)
        return JsonResponse(code = 20000, data = user.first().to_json(), message = "请求成功").jsonExit()

    except Exception as e:
        app.logger.error(Exception(e))
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 用户编辑
@user_route.route('/edit', methods = ['POST'])
@check_param(paramList = ['id'])
def userEdit():
    try:
        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(User).filterField(form)

        user = User.objects(id = form.get('id'), admin = ADMIN)
        if user.count() == 0:
            return JsonResponse(code = 40005, data = None, message = "用户不存在").jsonExit()
        user.update(**form)
        return JsonResponse(code = 20000, data = user.exclude('password'), message = "请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 用户删除
@user_route.route('/delete', methods = ['POST'])
@check_param(paramList = ['id'])
def userDelete():
    try:
        form = {} if not request.json else dict(request.json)
        user = User.objects(id = form.get('id'), admin = ADMIN)
        if user.count() == 0:
            return JsonResponse(code = 40005, data = None, message = "用户不存在").jsonExit()
        user.delete()
        return JsonResponse(code = 20000, data = None, message = "请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 用户登录
@user_route.route('/login', methods = ['POST'])
@check_param(paramList = ['username', 'password'])
def userLogin():
    try:
        form = {} if not request.json else dict(request.json)
        username, password = form.get('username'), form.get('password')
        user_name = User.objects(username = username, admin = ADMIN)
        user_phone = User.objects(phone = username, admin = ADMIN)

        if user_name.count() == 0 and user_phone.count() == 0:
            return JsonResponse(code = 40003, data = None, message = "用户不存在").jsonExit()
        if user_name.count() == 0:
            user = user_phone
        else:
            user = user_name
        if user.first().password != password:
            return JsonResponse(code = 40004, data = None, message = "密码错误").jsonExit()

        return JsonResponse(code = 20000, data = user.first().login_to_json(), message = "请求成功").jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()


# 用户退出登录
@user_route.route('/logout', methods = ['POST'])
def userLogout():
    try:
        return JsonResponse(code = 20000, data = None, message = "请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()
